package com.snailcatmall.www.serversocket.netty;

import com.snailcatmall.www.serversocket.tools.GlobalStaticClass;
import io.netty.channel.*;
import io.netty.channel.socket.nio.NioServerSocketChannel;


/**
 * @see NettyTcpSocketNio 创建服务端
 */
public class NettyTcpSocketNio {

    public void openTcpSocketServer(int port){
        try {
            GlobalStaticClass.serverBootstrap.group(GlobalStaticClass.bossGroup, GlobalStaticClass.workerGroup);
            GlobalStaticClass.serverBootstrap.channel(NioServerSocketChannel.class);
            GlobalStaticClass.serverBootstrap.option(ChannelOption.SO_KEEPALIVE,true);
            GlobalStaticClass.serverBootstrap.childOption(ChannelOption.ALLOW_HALF_CLOSURE,false);
            GlobalStaticClass.serverBootstrap.childOption(ChannelOption.AUTO_READ,true);
            GlobalStaticClass.serverBootstrap.childOption(ChannelOption.TCP_NODELAY,true);
            GlobalStaticClass.serverBootstrap.childHandler(new NettyChannelInitializer());
            ChannelFuture channelFuture = GlobalStaticClass.serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){e.printStackTrace();}finally {
            GlobalStaticClass.workerGroup.shutdownGracefully();
            GlobalStaticClass.bossGroup.shutdownGracefully();
        }

    }
}
